package com.payment.ktb.activity.main1;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.AlertInterface;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.activity.main4.BasicalInfoActivity;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.DeviceUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/8.
 */
public class WeixinOrderCreateActivity extends BaseActivity {


    String linkId = "";

    @BindView(R.id.et_weixinordercreate_amount)
    EditText et_weixinordercreate_amount;

    @BindView(R.id.tv_nocardordercreate_amountMin)
    TextView tv_nocardordercreate_amountMin;
    @BindView(R.id.tv_nocardordercreate_amountMax)
    TextView tv_nocardordercreate_amountMax;
    @BindView(R.id.tv_nocardordercreate_time)
    TextView tv_nocardordercreate_time;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_weixinordercreate);
        ButterKnife.bind(this);
        initTitle("微信收款");
        tv_nocardordercreate_amountMin.setText(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMin) + "元");
        tv_nocardordercreate_amountMax.setText(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMax) + "元");
        String nocardOrderStart = SharedPreferencesUtils.getString(ConstantsPay.nocardOrderStart);
        String nocardOrderEnd = SharedPreferencesUtils.getString(ConstantsPay.nocardOrderEnd);
        tv_nocardordercreate_time.setText(nocardOrderStart + "-" + nocardOrderEnd);
    }


    @OnClick({R.id.btn_weixinordercreate_next})
    public void clickEvent(View view) {

        switch (view.getId()) {

            //收款
            case R.id.btn_weixinordercreate_next:
                if (checkAmount()) {
                    submit("20");
                }
                break;

        }



    }


    /**
     *
     */
    private boolean checkAmount() {
        String temp = et_weixinordercreate_amount.getText().toString().trim();
        if (TextUtils.isEmpty(temp)) {
            ToastUtils.showToast("请输入金额！");
            return false;
        }

        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMin)) && Double.parseDouble(temp) < Double.parseDouble(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMin))) {
            ToastUtils.showToast("交易金额不能小于" + SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMin));
            return false;
        }
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMax))  && Double.parseDouble(temp) > Double.parseDouble(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMax))) {
            ToastUtils.showToast("交易金额不能大于" + SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMax));
            return false;
        }

        return true;
    }


    /**
     *
     */
    private void submit(String type) {


        progressDialogUtils.showProgress();

        //构造传输参数

        final String orderType = type;
        final String amount = et_weixinordercreate_amount.getText().toString().trim();
        String version = DeviceUtils.getVersionName();
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //
        String sign = Md5Utils.md5Hex(amount + linkId + orderType + version + SharedPreferencesUtils.getString(ConstantsUser.userKey));

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("linkId",linkId);
        map.put("orderType",orderType);
        map.put("amount",amount);
        map.put("version",version);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.weixinOrderCreateState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        ConstantsPay.amount = amount;
                        ConstantsPay.orderType = orderType;
                        ConstantsPay.orderNo = jsonObject.optString("orderNo");
                        ConstantsPay.orderTime = jsonObject.optString("orderTime");
                        ConstantsPay.qrcode = jsonObject.optString("qrcode");
                        startActivity(WeixinOrderConfirmActivity.class);

                    } else if ("ERR504".equals(code)) {


                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"), "取消", "去认证", new AlertInterface() {
                            @Override
                            public void confirm(Dialog alertDialog) {
                                getShopInfo();

                            }
                        });


                    } else {

                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();

        linkId = String.valueOf(new Date().getTime());

    }





    /**
     * 商户信息查询
     * @return
     */
    public void getShopInfo() {


        progressDialogUtils.showProgress();

        //构造传输参数
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //MD5（picNbr+key）
        String sign = Md5Utils.md5Hex(SharedPreferencesUtils.getString(ConstantsUser.userKey));

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.shopInfoState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        ConstantsUser.isEdit = jsonObject.optString("isEdit");
                        ConstantsUser.shopStatus = jsonObject.optString("shopStatus");
                        ConstantsUser.shopStatusCn  = jsonObject.optString("shopStatusCn");
                        ConstantsUser.selfStatus  = jsonObject.optString("selfStatus");
                        SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPCERT,jsonObject.optString("shopCert"));
                        SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPACCOUNT,jsonObject.optString("shopAccount"));
                        SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPBANK,jsonObject.optString("shopBank"));
                        SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1,jsonObject.optString("pic1"));
                        SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2,jsonObject.optString("pic2"));
                        SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC3,jsonObject.optString("pic3"));
                        SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4,jsonObject.optString("pic4"));
                        ConstantsUser.picQr = jsonObject.optString("picQr");
                        ConstantsUser.showMsg = jsonObject.optString("showMsg");
                        ConstantsUser.orgId = jsonObject.optString("orgId");
                        ConstantsUser.activationStatus = jsonObject.optString("activationStatus");
                        startActivity(BasicalInfoActivity.class);

                    } else {

                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });

    }






}
